package org.jsola.hr.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import org.jsola.core.Page;
import org.jsola.exception.ParamException;
import org.jsola.hr.common.ExampleKit;
import org.jsola.hr.common.HrLogKit;
import org.jsola.hr.constant.CrmMemberJurisdictionType;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dao.ICrmMemberDAO;
import org.jsola.hr.dto.*;
import org.jsola.hr.entity.CrmMemberDO;
import org.jsola.hr.provider.IUserProviderService;
import org.jsola.hr.query.CrmMemberQuery;
import org.jsola.hr.query.CrmMemberRelationQuery;
import org.jsola.hr.query.HrUserQuery;
import org.jsola.hr.service.*;
import org.jsola.hr.vo.*;
import org.jsola.log.common.LogKit;
import org.jsola.user.core.TokenUser;
import org.jsola.user.entity.UserDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 成员表
 *
 * @author zhr
 */
@Service("hrCrmMemberServiceImpl")
public class CrmMemberServiceImpl implements ICrmMemberService {

    @Autowired
    private ICrmMemberDAO crmMemberDAO;
    @Autowired
    private ICrmCustomerInfoService crmCustomerInfoService;
    @Autowired
    private ICrmCustomerDistributionRecordService crmCustomerDistributionRecordService;
    @Autowired
    private ICrmMemberRelationService crmMemberRelationService;
    @Autowired
    private ICrmOperationRecordService crmOperationRecordService;
    @Autowired
    private IUserProviderService userProviderService;

    @Override
    public List<CrmMemberVO> getMyManagerList(TokenUser tokenUser) {
        List<CrmMemberVO> crmMemberVOS = new ArrayList<>();
        //查询自己的memberid
        CrmMemberQuery crmMemberQuery = new CrmMemberQuery();
        crmMemberQuery.setUserId(tokenUser.getUserId());
        List<CrmMemberListVO> select = select(crmMemberQuery, tokenUser.getSiteId());
        if(CollectionUtils.isEmpty(select)){
            return crmMemberVOS;
        }

        CrmMemberRelationQuery crmMemberRelationQuery = new CrmMemberRelationQuery();
        crmMemberRelationQuery.setSuperiorMemberId(select.get(0).getId());
        List<CrmMemberRelationListVO> select1 = crmMemberRelationService.select(crmMemberRelationQuery, tokenUser.getSiteId());
        for (CrmMemberRelationListVO crmMemberRelationListVO : select1) {
            CrmMemberVO crmMemberVO = selectById(crmMemberRelationListVO.getMemerId(), tokenUser.getSiteId());
            crmMemberVOS.add(crmMemberVO);
        }
        return crmMemberVOS;
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public Void addRange(CrmMemberQuery crmMemberQuery, TokenUser tokenUser) {
        //删除下属
        CrmMemberRelationQuery crmMemberRelationQuery = new CrmMemberRelationQuery();
        crmMemberRelationQuery.setSuperiorMemberId(crmMemberQuery.getId());
        List<CrmMemberRelationListVO> select = crmMemberRelationService.select(crmMemberRelationQuery, tokenUser.getSiteId());
        for (CrmMemberRelationListVO crmMemberRelationListVO : select) {
            crmMemberRelationService.deleteByIds(tokenUser,crmMemberRelationListVO.getId());
        }
        if(ArrayUtil.isNotEmpty(crmMemberQuery.getMemberIds()) && crmMemberQuery.getJurisdiction() == 1){
            //新增下属
            List<String> memberIds = Arrays.asList(crmMemberQuery.getMemberIds());
            for (String memberId : memberIds) {
                CrmMemberRelationAddDTO crmMemberRelationAddDTO = new CrmMemberRelationAddDTO();
                crmMemberRelationAddDTO.setMemerId(memberId);
                crmMemberRelationAddDTO.setSuperiorMemberId(crmMemberQuery.getId());
                crmMemberRelationService.save(crmMemberRelationAddDTO,tokenUser);
            }

        }
        return null;
    }

    @Override
    public List<CrmMemberVO> getMyManager(String memberId, TokenUser tokenUser) {
        CrmMemberRelationQuery crmMemberRelationQuery = new CrmMemberRelationQuery();
        List<CrmMemberVO> crmMemberVOList = new ArrayList<>();
        crmMemberRelationQuery.setSuperiorMemberId(memberId);
        List<CrmMemberRelationListVO> select = crmMemberRelationService.select(crmMemberRelationQuery, tokenUser.getSiteId());
        for (CrmMemberRelationListVO crmMemberRelationListVO : select) {
            CrmMemberVO crmMemberVO = selectById(crmMemberRelationListVO.getMemerId(), tokenUser.getSiteId());
            crmMemberVOList.add(crmMemberVO);
        }
        return crmMemberVOList;
    }

    @Override
    public List<CrmMemberVO> getAllUser(CrmMemberQuery crmMemberQuery, TokenUser tokenUser) {
        List<CrmMemberVO> list1 = new ArrayList<>();
        List<CrmMemberVO> list = new ArrayList<>();
        if(crmMemberQuery.getStatus() ==1){
            List<HrUserVO> hrUserVOS = userProviderService.queryUserList(new HrUserQuery(), tokenUser);
            List<CrmMemberListVO> crmMemberListVOS = select(new CrmMemberQuery(), tokenUser.getSiteId());
            Map<String, HrUserVO> stringHrUserVOMap = hrUserVOS.stream().collect(Collectors.toMap(HrUserVO::getId, p -> p));
            for (CrmMemberListVO crmMemberListVO : crmMemberListVOS) {
                stringHrUserVOMap.remove(crmMemberListVO.getUserId());
            }
            for (String s : stringHrUserVOMap.keySet()) {
                list1.add(stringHrUserVOMap.get(s).to(CrmMemberVO.class));
            }
        }else if(crmMemberQuery.getStatus() == 2){
            CrmMemberRelationQuery crmMemberRelationQuery = new CrmMemberRelationQuery();
            if(!StringUtils.isEmpty(crmMemberQuery.getId())){
                crmMemberRelationQuery.setSuperiorMemberId(crmMemberQuery.getId());
            }
            List<CrmMemberRelationListVO> select1 = crmMemberRelationService.select(crmMemberRelationQuery, tokenUser.getSiteId());
            CrmMemberQuery crmMemberQuery1 = new CrmMemberQuery();
            crmMemberQuery1.setJurisdiction(2);
            List<CrmMemberListVO> select = select(crmMemberQuery1, tokenUser.getSiteId());
            Map<String, CrmMemberListVO> map = select.stream().collect(Collectors.toMap(CrmMemberListVO::getId, p -> p));
            for (CrmMemberRelationListVO crmMemberRelationListVO : select1) {
                if(map.containsKey(crmMemberRelationListVO.getMemerId())){
                    map.get(crmMemberRelationListVO.getMemerId()).setIsSubordinate(true);
                }
            }
            for (String key : map.keySet()) {
                CrmMemberListVO crmMemberListVO = map.get(key);
                if(crmMemberListVO.getIsSubordinate() == null){
                    crmMemberListVO.setIsSubordinate(false);
                }
                list1.add(crmMemberListVO.to(CrmMemberVO.class));
            }

        }
        if(!StringUtils.isEmpty(crmMemberQuery.getName())){
            for (CrmMemberVO crmMemberVO : list1) {
                if(!StringUtils.isEmpty(crmMemberVO.getName()) && crmMemberVO.getName().contains(crmMemberQuery.getName())){
                    list.add(crmMemberVO);
                }
            }
            list = list.parallelStream().filter(crmMemberVO -> !crmMemberVO.getId().equals(crmMemberQuery.getId())).collect(Collectors.toList());
            return list;
        }
        list1 = list1.parallelStream().filter(crmMemberVO -> !crmMemberVO.getId().equals(crmMemberQuery.getId())).collect(Collectors.toList());
        return list1;
    }

    @Override
    public List<HrUserVO> getJurisdictionRange(HrUserQuery hrUserQuery,TokenUser tokenUser) {
        List<HrUserVO> list = new ArrayList<>();
        //全部用户
        List<HrUserVO> hrUserVOS = userProviderService.queryUserList(new HrUserQuery(), tokenUser);
        Map<String, HrUserVO> userMap = hrUserVOS.stream().collect(Collectors.toMap(HrUserVO::getId, p -> p));
        //客户经理的userID
        CrmMemberQuery crmMemberQuery = new CrmMemberQuery();
        crmMemberQuery.setJurisdiction(1);
        List<CrmMemberListVO> select = select(crmMemberQuery, tokenUser.getSiteId());
        for (CrmMemberListVO crmMemberListVO : select) {
            userMap.remove(crmMemberListVO.getUserId());
        }
        userMap.remove(hrUserQuery.getUserId());
        for (String id : userMap.keySet()) {
            list.add(userMap.get(id));
        }
        return list;
    }

    @Override
    public Page<CrmMemberListVO> getUserPhone(Page<CrmMemberListVO> crmMemberListVOPage, TokenUser tokenUser) {
        for (CrmMemberListVO entity : crmMemberListVOPage.getEntities()) {
            UserDO userDO = userProviderService.selectUserById(entity.getUserId());
            if(userDO != null && !StringUtils.isEmpty(userDO.getPhone())){
                entity.setPhone(userDO.getPhone());
            }
        }
        return crmMemberListVOPage;
    }

    @Override
    public Boolean permissionVerification(TokenUser tokenUser, int type) {
        CrmMemberQuery crmMemberQuery = new CrmMemberQuery();
        crmMemberQuery.setUserId(tokenUser.getUserId());
        List<CrmMemberListVO> select = select(crmMemberQuery, tokenUser.getSiteId());
        if(select == null || select.size()==0){
            //throw new ParamException("用户未配置权限");
        }else {
            return select.get(0).getJurisdiction()==type;
        }
        return false;
    }

    @Override
    public Integer updateJurisdiction(CrmMemberQuery crmMemberQuery1, TokenUser tokenUser) {
        //查询是否客户经理
        CrmMemberQuery crmMemberQuery = new CrmMemberQuery();
        crmMemberQuery.setUserId(tokenUser.getUserId());
        List<CrmMemberListVO> select = select(crmMemberQuery, tokenUser.getSiteId());
        if(select == null || select.size()==0){
      //      throw new ParamException("使用的账号无权限使用此功能");
            return null;
        }
        if(select.get(0).getJurisdiction() != CrmMemberJurisdictionType.MANAGER.getValue().intValue()){
       //    throw new ParamException("使用的账号无权限使用此功能");
            return null;
        }
        LogKit.logForUpdate("CRM配置用户权限","updateJurisdiction",crmMemberQuery1.getId(),tokenUser);
        //权限范围
        addRange(crmMemberQuery1,tokenUser);
        //修改权限
        CrmMemberUpdateDTO crmMemberUpdateDTO = new CrmMemberUpdateDTO();
        crmMemberUpdateDTO.setId(crmMemberQuery1.getId());
        crmMemberUpdateDTO.setJurisdiction(crmMemberQuery1.getJurisdiction());
        return update(crmMemberUpdateDTO, tokenUser);
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public CrmMemberVO addJurisdiction(CrmMemberAndCustomerAddDTO crmMemberAndCustomerAddDTO, TokenUser tokenUser) {
        CrmMemberQuery crmMemberQuery1 = new CrmMemberQuery();
        crmMemberQuery1.setUserId(crmMemberAndCustomerAddDTO.getUserId());
        List<CrmMemberListVO> select1 = select(crmMemberQuery1, tokenUser.getSiteId());
        if(CollectionUtil.isNotEmpty(select1)){
            throw new ParamException("该成员已配置权限");
        }
        //新增人员权限
        CrmMemberVO crmMemberVO = save(crmMemberAndCustomerAddDTO.to(CrmMemberAddDTO.class), tokenUser);
        if(crmMemberAndCustomerAddDTO.getJurisdiction()==2){
            //todo 2022-1-25 :产品要求新增客户专员默认不属于任何客户经理
//            CrmMemberQuery crmMemberQuery = new CrmMemberQuery();
//            crmMemberQuery.setUserId(tokenUser.getUserId());
//            List<CrmMemberListVO> select = select(crmMemberQuery, tokenUser.getSiteId());
//            if(select != null && select.size() > 0){
//                CrmMemberRelationAddDTO crmMemberRelationAddDTO = new CrmMemberRelationAddDTO();
//                crmMemberRelationAddDTO.setMemerId(crmMemberVO.getId());
//                crmMemberRelationAddDTO.setSuperiorMemberId(select.get(0).getId());
//                crmMemberRelationService.save(crmMemberRelationAddDTO,tokenUser);
//            }
        }//成员关系
        else if(crmMemberAndCustomerAddDTO.getJurisdiction()==1 && crmMemberAndCustomerAddDTO.getMemberIds() != null){
            for (String memberId : crmMemberAndCustomerAddDTO.getMemberIds()) {
                CrmMemberRelationAddDTO crmMemberRelationAddDTO = new CrmMemberRelationAddDTO();
                crmMemberRelationAddDTO.setMemerId(memberId);
                crmMemberRelationAddDTO.setSuperiorMemberId(crmMemberVO.getId());
                crmMemberRelationService.save(crmMemberRelationAddDTO,tokenUser);
            }
        }
        HrLogKit.logForSave("新增权限用户","addJurisdiction",crmMemberVO.getId(),tokenUser);
        return crmMemberVO;
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public CrmMemberVO save(CrmMemberAddDTO crmMemberAddDTO, TokenUser tokenUser) {
//        //校验是否存在
//        CrmMemberQuery crmMemberQuery = crmMemberAddDTO.to(CrmMemberQuery.class);
//        List<CrmMemberListVO> select = select(crmMemberQuery, tokenUser.getSiteId());
//        if(!CollectionUtils.isEmpty(select)){
//            return new CrmMemberVO();
//        }
        // 转DO
        CrmMemberDO crmMemberDO = crmMemberAddDTO.to(CrmMemberDO.class);
        // 保存
        crmMemberDO = save(crmMemberDO, tokenUser.getSiteId(), tokenUser.getUserId());
        return crmMemberDO.to(CrmMemberVO.class);
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int update(CrmMemberUpdateDTO crmMemberUpdateDTO, TokenUser tokenUser) {
        //转DO
        CrmMemberDO crmMemberDO = crmMemberUpdateDTO.to(CrmMemberDO.class);
        //根据主键更新，只更新非null值
        return updateByIdSelective(crmMemberDO, tokenUser.getSiteId(), tokenUser.getUserId());
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int deleteByIds(TokenUser tokenUser, String... crmMemberIds) {
        return logicalDeleteByIds(tokenUser.getSiteId(), tokenUser.getUserId(), (Object[]) crmMemberIds);
    }

    @Override
    public CrmMemberVO selectByIdNotSiteId(String crmMemberId) {
        Example example = new Example(CrmMemberDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("id", crmMemberId);
        CrmMemberDO crmMemberDO = crmMemberDAO.selectOneByExample(example);
        return crmMemberDO.to(CrmMemberVO.class);
    }

    @Override
    public CrmMemberVO selectById(String crmMemberId, String siteId) {
        CrmMemberDO crmMemberDO = selectDOById(crmMemberId, siteId);
        if (crmMemberDO == null) {
            return null;
        }
        return crmMemberDO.to(CrmMemberVO.class);
    }

    @Override
    public List<CrmMemberListVO> select(CrmMemberQuery crmMemberQuery, String siteId) {
        List<CrmMemberDO> crmMemberDOList = selectDO(crmMemberQuery, siteId);
        if(CollectionUtils.isEmpty(crmMemberDOList)) {
            return crmMemberDOList == null ? null : new ArrayList<>();
        }
        return crmMemberDOList.stream()
                .map(crmMemberDO -> crmMemberDO.to(CrmMemberListVO.class))
                .collect(Collectors.toList());
    }

    @Override
    public int selectCount(CrmMemberQuery crmMemberQuery, String siteId) {
        Example example = buildExample(crmMemberQuery,siteId);
        return crmMemberDAO.selectCountByExample(example);
    }

    @Override
    public Page<CrmMemberListVO> selectPage(CrmMemberQuery crmMemberQuery, String siteId) {
        Example example = buildExample(crmMemberQuery,siteId);
        Page<CrmMemberDO> page = crmMemberDAO.selectPageByExample(example,
                crmMemberQuery.getPageNo(),
                crmMemberQuery.getPageSize());
        return page.to(CrmMemberListVO.class);
    }

    @Override
    public CrmMemberDO selectDOById(String crmMemberId, String siteId) {
        return listById(crmMemberId, siteId);
    }

    @Override
    public List<CrmMemberDO> selectDO(CrmMemberQuery crmMemberQuery, String siteId) {
        Example example = buildExample(crmMemberQuery,siteId);
        return crmMemberDAO.selectByExample(example);
    }


    /**
     * 根据查询参数，构建example

     * @param crmMemberQuery 查询参数
     * @param siteId 所属站点id
     * @return example
     */
    private Example buildExample(CrmMemberQuery crmMemberQuery, String siteId) {
        Example example = new Example(CrmMemberDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", siteId);
        // 排序
        if(!StringUtils.isEmpty(crmMemberQuery.getUserId())){
            example.and().andEqualTo("userId",crmMemberQuery.getUserId());
        }
        if(crmMemberQuery.getJurisdiction() != null){
            example.and().andEqualTo("jurisdiction",crmMemberQuery.getJurisdiction());
        }
        if(!StringUtils.isEmpty(crmMemberQuery.getName())){
            example.and().andLike("name","%"+crmMemberQuery.getName()+"%");
        }
        if(CollectionUtil.isNotEmpty(crmMemberQuery.getMemberIdList())){
            example.and().andIn("id",crmMemberQuery.getMemberIdList());
        }
        ExampleKit.setExampleOrder(example,crmMemberQuery.getOrders());
        return example;
    }
}




